package com.bcn.login_mybatisplus_demo.interceptor;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.bcn.login_mybatisplus_demo.constant.CustomException;
import com.bcn.login_mybatisplus_demo.constant.HttpStatus;
import com.bcn.login_mybatisplus_demo.saraca.pojo.AppUser;
import com.bcn.login_mybatisplus_demo.saraca.mapper.AppUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 *
 * @author
 */
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    public AppUserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

     if(request.getRequestURL().toString().contains("app/user/register") || request.getRequestURL().toString().contains("app/user/login")|| request.getRequestURL().toString().contains("upload")){
         return true;
     }

        System.out.println("开始拦截 AuthInterceptor.........");

        String token = request.getHeader("Authorization");
        if (token == null || token.equals("")) {
            throw new CustomException("token为空", HttpStatus.UNAUTHORIZED);
        }


        //获取token中的id
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (Exception e) {
            throw new CustomException("该token不正确", HttpStatus.UNAUTHORIZED);
        }

        //判断该id的用户是否存在
        AppUser user = userMapper.getById(userId);
        if (user == null) {
            throw new CustomException("该用户已经不存在", HttpStatus.UNAUTHORIZED);
        }


        //核心：进行验证
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token);
        } catch (Exception e) {
            throw new CustomException("验证token时出错", HttpStatus.UNAUTHORIZED);
        }
        AuthStorage.setUser(token, user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完成清除授权信息
        AuthStorage.clearUser();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }


}
